package com.hinnotek.warehouse

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.WindowManager
import android.widget.ImageView
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.github.chrisbanes.photoview.PhotoView
import kotlin.math.roundToInt

/**
 * 根据传入的宽度，放大高度
 */
class PhotoViewImageViewTarget(var photoView: PhotoView) :
    CustomTarget<Drawable>() {

    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable?>?) {
        if (photoView.scaleType != ImageView.ScaleType.FIT_XY) {
            photoView.scaleType = ImageView.ScaleType.FIT_XY;
        }
        val wm = photoView.context
            .getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val width = wm.defaultDisplay.width;
        val params = photoView.layoutParams;
        params.width = width;
        val vw = photoView.width - photoView.paddingLeft - photoView.getPaddingRight();
        val scale = vw.toFloat() / resource.intrinsicWidth.toFloat()
        val vh = (resource.intrinsicHeight * scale).roundToInt();
        params.height = vh + photoView.paddingTop + photoView.paddingBottom
        photoView.layoutParams = params;
        photoView.setImageDrawable(resource)
    }

    override fun onLoadCleared(placeholder: Drawable?) {

    }
}